﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Xml.Serialization;

namespace Utilities
{
    /// <summary>
    ///JsonHelper 的摘要说明
    /// </summary>
    public class JsonHelper
    {
        /// <summary>
        /// 将obj对象序列化成JSON字符串
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns>JSON字符串</returns>
        public static string SerializeObject(Object obj)
        {
            string json = "";
            DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                ser.WriteObject(ms, obj);
                json = System.Text.Encoding.UTF8.GetString(ms.ToArray());
            }
            return json;
        }
        /// <summary>
        /// 将JSON字符串序反列化为指定T型的对象
        /// </summary>
        /// <typeparam name="T">目标类型</typeparam>
        /// <param name="json">json字符串</param>
        /// <returns>T类型的对象</returns>
        public static T DeSerializeObject<T>(string json)
        {
            System.Text.UTF8Encoding utf = new System.Text.UTF8Encoding();

            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            using (System.IO.MemoryStream s = new System.IO.MemoryStream(utf.GetBytes(json)))
            {
                return (T)ser.ReadObject(s);
            }
        }
    }
    
}